<template>
  <view class="circular-progress-bar-container">
    <canvas canvas-id="circularProgressBar" :style="{ width: width + 'px', height: height + 'px' }"></canvas>
    <span class="text">{{progress}}%</span>
  </view>
</template>

<script>
export default {
  name: 'CircularProgressBar',
  props: {
    progress: {
      type: Number,
      required: true,
      validator: value => value >= 0 && value <= 100
    },
    width: {
      type: Number,
      default: 55
    },
    height: {
      type: Number,
      default: 55
    },
    strokeWidth: {
      type: Number,
      default: 5
    },
    backgroundColor: {
      type: String,
      default: '#e0e0e0'
    },
    foregroundColor: {
      type: String,
      default: '#8287FA'
    }
  },
  mounted() {
    this.draw();
  },
  watch: {
    progress() {
      this.draw();
    }
  },
  methods: {
    draw() {
      const ctx = uni.createCanvasContext('circularProgressBar', this);
      const centerX = this.width / 2;
      const centerY = this.height / 2;
      const radius = Math.min(centerX, centerY) - this.strokeWidth / 2;
      const circumference = 2 * Math.PI * radius;
      const offset = circumference - (this.progress / 100) * circumference;

      // Clear the canvas
      ctx.clearRect(0, 0, this.width, this.height);

      // Set line styles
      ctx.setLineWidth(this.strokeWidth);
      ctx.setLineCap('round');

      // Draw background circle
      ctx.setStrokeStyle(this.backgroundColor);
      ctx.beginPath();
      ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI);
      ctx.stroke();

      // Draw foreground circle (progress)
      ctx.setStrokeStyle(this.foregroundColor);
      ctx.beginPath();
      ctx.arc(centerX, centerY, radius, -Math.PI / 2, (this.progress / 100) * 2 * Math.PI - Math.PI / 2);
      ctx.stroke();

      // Draw the canvas
      ctx.draw();
    }
  }
};
</script>

<style lang="scss" scoped>
.circular-progress-bar-container {
  display: inline-block;
  position: relative;
  .text{
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%,-50%);
  }
}
</style>